
import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:rfid/widget/dialog_widget.dart';
import '../entity/book_entity.dart';
import '../entity/place_entity.dart';
import '../event/inventory_rfid_event.dart';
import '../event/lock_state_event.dart';
import '../hive/hive_helper.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/socket.dart';
import '../util/analysis_book_rule.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/device_name_widget.dart';
import '../widget/focus_killer.dart';
import 'help_page.dart';


class BorrowResult extends StatefulWidget {
  const BorrowResult({Key? key}) : super(key: key);

  @override
  State<BorrowResult> createState() => _BorrowResultState();
}

class _BorrowResultState extends State<BorrowResult> {

  RxList<BookEntity> borrowList = RxList();
  RxList<BookEntity> returnList = RxList();

  StreamSubscription? actionSubscription;
  StreamSubscription? lockSubscription;

  bool isDoorShow = false;

  _inventory(){
    BotToast.showLoading(clickClose: true);
    if(settingEntity.isUltra!){
      socketHelper.add(inventoryUhfRfid(readerIp: currentTask.readerIp!,ant: currentTask.ant!,count: settingEntity.scanTime!));
    }else{
      socketHelper.add(inventoryHfRfid(readerIp: currentTask.readerIp!,ant: currentTask.ant!,count: settingEntity.scanTime!,blockStart:settingEntity.blockStart,blockCount:settingEntity.blockCount));
    }
  }

  @override
  initState() {
    super.initState();

    _inventory();
    lockSubscription = eventFactory.on<LockStateEvent>().listen((event) {

      if(event.state == 1){
        _inventory();
        timer.startCountDown(CountDownMode.fast,(){
          _setResult();
        });
      }
    });

    actionSubscription = eventFactory.on<InventoryRfidEvent>().listen((event) async {
      var entity = event.entity;
      if(entity.list != null ){
          List<String> currentList = [];
          var allBook = bookQueryByDoorNo(currentTask.doorNo!);
          var preList = allBook.where((element) => element.statue == 0).map((e) => e.no);
          List<String> returnArr = [];
          List<String> borrowArr = [];
          returnList.clear();
          borrowList.clear();
          for (var item in entity.list!) {
            try{
              var id = '';
              if(settingEntity.isUltra!){
                id = item.epc!;
              }else{
                id = item.blockData!;
              }
              // var length = int.parse(id.substring(0,2));
              // var bookNo = id.substring(2, length+2);
              var bookNo = analysisBookRule(id);
              if(bookNo!=null){
                currentList.add(bookNo);
              }
            }catch(e){
              toastWarn("条码号异常");
            }
          }

          //借出
          for (var element in preList) {
            if(!currentList.contains(element)){
              borrowArr.add(element!);
            }
          }
          //归还
          for (var element in currentList) {
            if(!preList.contains(element)){
              returnArr.add(element);
            }
          }
          // print("currentList = ${currentList.join(',')}");
          // print("preList = ${preList.join(',')}");
          // print("returnArr = ${returnArr.join(',')}");
          // print("borrowArr = ${borrowArr.join(',')}");
          for (var element in returnArr) {
            var book = bookQuery(element);
            if(book != null){
              if(book.statue == 1){
                returnList.add(book);
              }
            }else{
              BotToast.showLoading(clickClose: true);
              var data = await findBook(element);
              BotToast.closeAllLoading();
              if(data != null ){
                data.doorNo = currentTask.doorNo!;
                bookInsert(element, data);
                returnList.add(data);
              }
            }
          }
          for (var element in borrowArr) {
            var book = bookQuery(element);
            if(book != null){
              borrowList.add(book);
            }
          }
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.fast,(){
        _setResult();
      });
    });

  }

  @override
  void dispose() {
    actionSubscription?.cancel();
    actionSubscription = null;
    lockSubscription?.cancel();
    lockSubscription  = null;
    super.dispose();
  }

  _appBar(){
    return Container(
      width: double.infinity,
      height: 42.h,
      alignment: Alignment.center,
      padding: const EdgeInsets.only(left: 20,right: 20).w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          deviceNameWidget(),
          InkWell(
            onTap: (){
              Get.to(()=> const Help());
            },
            child:  Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                focusKiller(),
                Icon(Icons.help,color: Colors.white,size: 20.sp,),
                Text(" 帮助",style: TextStyle(color: Colors.white,fontSize: 12.sp),)
              ],
            ),
          )

        ],
      ),
    );
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 20.h,left: 20.w,right: 20.w,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(''),
            _image("assets/images/borrow_result_title.png",90.w,21.h),
            Obx(() => Text("${timer.fastTime.value}s",style: TextStyle(color: Colors.white,fontSize: 12.sp),))
          ],
        )
    );
  }

  _confirm(){
    return InkWell(
      onTap: ()  {
        _setResult();
      },
      child:  _image("assets/images/result_confirm.jpg", 80.w, 36.h),
    );
  }

  _setResult() async {
    var showOver = false;
    var list = [];
    for(var item in returnList){
      item.statue = 0;
      item.doorNo = currentTask.doorNo!;
      bookInsert(item.no, item);
      var res = await bookReturn(item.no);
      if(res != null){
        currentTask.offset = currentTask.offset +1;
      }
      list.add(
          PlaceEntity()
            ..bookNo = item.no
            ..place = '${settingEntity.index}${currentTask.doorNo?.padLeft(2,'0')}格'
      );
    }

    for(var item in borrowList){
      item.statue = 1;
      bookInsert(item.no, item);
      if(currentTask.offset>0){
        var res = await bookBorrow(currentTask.uid,item.no);
        if(res != null){
          currentTask.offset = currentTask.offset - 1;
        }
      }else{
        showOver = true;
        await bookBorrowCommon(settingEntity.commonUid,item.no,currentTask.uid);
      }
      list.add(
          PlaceEntity()
            ..bookNo = item.no
            ..place = ''
      );
    }
    sendPlace(list);
    Future.delayed(const Duration(milliseconds: 200),(){
      timer.cancel();
      currentTask.clear();
      DialogWidget().borrowOverDialog(showOver: showOver);
    });

  }

  _error(){
    return InkWell(
      onTap: (){
        socketHelper.add(lockOpen(addr: currentTask.addr!, no: currentTask.lock!));
      },
      child:  Text('信息有误？重新操作',style: TextStyle(fontSize: 6.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),
    );
  }

  _listTitle(title){
    return Container(
      // width: 300.w,
      height: 20.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(86, 169, 255, 1),
        borderRadius: BorderRadius.only(topLeft:Radius.circular(4.r),topRight: Radius.circular(4.r)),
      ),
      alignment: Alignment.center,
      child: Text(title,style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),),
    );
  }

  _listLabel(){
    return Container(
      padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _label('序号',50.w),
          _label('图书条码号',105.w),
          _label('图书名称',105.w),
          _label('操作结果',50.w),
        ],
      )
    );
  }

  _label(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp),textAlign: TextAlign.center,),
    );
  }
  _divider(){
    return Divider(
      height: 0.5.h, // Divider 组件高度
      indent: 4.w, // 分割线左侧间距
      endIndent: 4.w, // 分割线右侧间距
      color: const Color.fromRGBO(86, 169, 255, 1),
    );
  }

  _item(text,width){
    return Container(
      width: width,
      alignment: Alignment.center,
      child: Text(text,style: TextStyle(color: Colors.black,fontSize: 8.sp),textAlign: TextAlign.center,),
    );
  }

  _listItem(list,index){
    var item = list[index];
    return Container(
        padding: EdgeInsets.only(top: 2.h,bottom: 2.h),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _item('${index+1}',50.w),
            _item('${item.no}',105.w),
            _item('${item.mainTitle}',105.w),
            _item('成功',50.w),
          ],
        )
    );
  }

  _list(list){
    return Expanded(
      child: ListView.separated(
        itemBuilder: (context, index) {
          return _listItem(list,index);
        },
        itemCount: list.length,
        separatorBuilder: (BuildContext context, int index) {
          return Divider(
            height: 0.5.h, // Divider 组件高度
            // thickness: 5, // 分割线线宽，分割线居于 Divider 中心
            indent: 4.w, // 分割线左侧间距
            endIndent: 4.w, // 分割线右侧间距
            color: Colors.grey,
          );
        },
      )
    );
  }

  _resultWidget(title, list){
    return Container(
      // width: 300.w,
      height: 200.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      margin: EdgeInsets.only(left: 20.w,right: 20.w,top: 10.h),
      child: Column(
        children: [
          _listTitle(title),
          _listLabel(),
          _divider(),
          _list(list)
        ],
      ),

    );
  }


  _image(name,width, height){
    return Image.asset(name,height: height, width: width, fit: BoxFit.fill,);
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _appBar(),
            _title(),
            Obx(() => _resultWidget('借书清单',borrowList)),
            Obx(() => _resultWidget('还书清单',returnList)),

            SizedBox(height: 20.h,),
            _confirm(),
            SizedBox(height: 10.h,),
            _error(),
          ],
        ),
      ),
    );
  }
}

